const path = require('path');
const fs = require('fs');
const { runLoaders } = require('./loader-runner.js');
let entry = path.resolve(__dirname, 'src/index.js'); // webpack的入口文件

// 行内loader
let request = `!inline-loader1!inline-loader2!${entry}`;

//module.rules = [] webpack配置loader
let rules = [
  {
    enforce: 'pre',
    test: /\.js$/,
    use: ['pre-loader1', 'pre-loader2']
  },
  {
    enforce: 'post',
    test: /\.js$/,
    use: ['post-loader1', 'post-loader2']
  },
  {
    test: /\.js$/,
    use: ['normal-loader1', 'normal-loader2']
  }
]


// 1.提取loader
let parts = request.replace(/^-?!+/, '').split("!")
let entryPath = parts.pop(); // d:\b-jiagou\webpack\05.loader\src\index.js
let inlineLoaders = parts; // ["inline-loader1","inline-loader2"]


let preLoaders = [], normalLoaders = [], postLoaders = [];

for (let i = 0; i < rules.length; i++) {
  let rule = rules[i];
  if (rule.test.test(entryPath)) {
    if (rule.enforce === 'pre') {
      preLoaders.push(...rule.use)
    } else if (rule.enforce === 'post') {
      postLoaders.push(...rule.use)
    } else {
      normalLoaders.push(...rule.use)
    }
  }
}

let loaders = [];
// 2.排列loader执行顺序
// loaders = [...postLoaders, ...inlineLoaders, ...normalLoaders, ...preLoaders];
/* 
特殊配置符号： -! 不要前置和普通 loader 、! 不要普通 loader、!! 不要前后置和普通 loader,只要内联 loader
*/
if (request.startsWith('!!')) {
  loaders = inlineLoaders;
} else if (request.startsWith('-!')) {
  loaders = [...postLoaders, ...inlineLoaders]
} else if (request.startsWith('!')) {
  loaders = [...postLoaders, ...inlineLoaders, ...preLoaders]
} else {
  loaders = [...postLoaders, ...inlineLoaders, ...normalLoaders, ...preLoaders];
}

// 3定义函数，生成loader的觉对路径
let resolveLoader = loader => path.resolve(__dirname, 'run-loader', loader);
loaders = loaders.map(resolveLoader)
console.log(entryPath, 'erntr')
runLoaders({
  resource: entryPath,
  loaders,
  context: { name: 'zb' },// 上下文对象 一般来说没有用，在loader中可以访问到
  readResource: fs.readFile
}, (err, result) => {
  console.log(err),
    console.log(result, 'result')
})




